<?php


namespace App\Http\Controllers\WebApi;


use App\Http\Controllers\WebApi\Business\OperationLogsBusiness;
use App\Models\ImEnterpriseCertification;
use App\Models\ImOperationLogs;
use App\Models\ImPersonalCertificate;
use App\Models\ImUsers;
use App\Validators\UserValidator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CertificationController
{
    /**
     * 用户审核列表
     * @param string searchWord 关键词搜索
     * @param integer status 状态搜索 0所有 1认证中 2已认证
     * @return \Illuminate\Http\JsonResponse
     */
    public function perCerList(Request $req)
    {
        $param = $req->all();
        list($offset, $limit, $page, $pagesize) = ImPersonalCertificate::pageProcess();
        $query = new ImPersonalCertificate();
        if (isset($param['searchWord'])) {
            $query->where(function ($sql) use ($param) {
                $sql->where('id', $param['searchWord']);
                $sql->orWhere('id_card_no', $param['searchWord']);
                $sql->orWhere('name', $param['searchWord']);
            });
        }
        if (isset($param['status']) && $param['status'] > 0) {
            $query->where('status', $param['status']);
        }
        $total = $query->count();
        $data = $query->offset($offset)->limit($limit)->orderBy('id', 'desc')->get();
        return okBack($data, [
            'total' => $total,
            'page' => $page,
            'pagesize' => $pagesize,
        ]);
    }

    /**
     * 个人认证审核
     * @param integer id 记录id
     * @param integer status 状态
     * @return \Illuminate\Http\JsonResponse
     */
    public function perCerAudit(Request $req)
    {
        $param = $req->all();
        $valid = UserValidator::handle($param, 'perCerAudit');
        if (true !== $valid) {
            return errBack($valid->first());
        }
        DB::beginTransaction();
        try {
            $record = ImPersonalCertificate::where('id', $param['id'])->first();
            if (!$record) {
                return errBack('记录不存在');
            }
            $user = ImUsers::find($record['user_id']);
            if (!$user) {
                return errBack('用户不存在');
            }
            $user->auth_status = $param['status'];
            //保存用户授权状态
            $user->save();

            $oldStatus = $record->status;
            $record->status = $param['status'];
            //保存记录审核状态
            $record->save();
            if ($oldStatus != $record->status) {
                OperationLogsBusiness::addLog(ImOperationLogs::UPDATE, '个人认证审核;状态:' .
                    ImPersonalCertificate::getStatus($record->status) . ';ID:' . $param['id']);
            }
            DB::commit();
            return okBack();
        } catch (\Exception $e) {
            DB::rollBack();
            return errBack('审核失败');
        }
    }

    /**
     * 删除个人认证记录
     * @param Request $req
     * @return \Illuminate\Http\JsonResponse
     */
    public function perCerDel(Request $req)
    {
        $param = $req->all();
        $ids = isset($param['ids']) ? json_decode($param['ids'], true) : [];
        if (empty($ids)) {
            return errBack();
        }
        $res = ImPersonalCertificate::whereIn('id', $ids)->where('status', '<>', 2)->delete();
        //添加操作日志
        if ($res) {
            OperationLogsBusiness::addLog(ImOperationLogs::DELETE, '删除个人认证;ID:' . join(',', $ids));
        }
        return okBack();
    }

    /**
     * 企业认证列表
     * @param Request $req
     * @return \Illuminate\Http\JsonResponse
     */
    public function entCerList(Request $req)
    {
        $param = $req->all();
        list($offset, $limit, $page, $pagesize) = ImPersonalCertificate::pageProcess();
        $query = ImEnterpriseCertification::with(['province', 'city', 'area']);
        if (isset($param['searchWord'])) {
            $query->where(function ($sql) use ($param) {
                $sql->where('id', $param['searchWord']);
                $sql->orWhere('id_card_no', $param['searchWord']);
                $sql->orWhere('name', $param['searchWord']);
            });
        }
        if (isset($param['status']) && $param['status'] > 0) {
            $query->where('status', $param['status']);
        }
        $total = $query->count();
        $data = $query->offset($offset)->limit($limit)->orderBy('id', 'desc')->get();
        $data = ImEnterpriseCertification::addressPress($data);
        return okBack($data, [
            'total' => $total,
            'page' => $page,
            'pagesize' => $pagesize,
        ]);
    }

    /**
     * 企业认证审核
     * @param Request $req
     * @return \Illuminate\Http\JsonResponse
     */
    public function entCerAudit(Request $req)
    {
        $param = $req->all();
        $valid = UserValidator::handle($param, 'entCerAudit');
        if (true !== $valid) {
            return errBack($valid->first());
        }
        $record = ImEnterpriseCertification::where('id', $param['id'])->first();
        if (!$record) {
            return errBack('记录不存在');
        }
        $oldStatus = $record->status;
        $record->status = $param['status'];
        $record->save();
        if ($oldStatus != $record->status) {
            OperationLogsBusiness::addLog(ImOperationLogs::UPDATE, '企业认证审核;状态:' .
                ImEnterpriseCertification::getStatus($record->status) . ';ID:' . $param['id']);
        }
        return okBack();
    }

    /**
     * 删除企业认证
     * @param Request $req
     * @return \Illuminate\Http\JsonResponse
     */
    public function entCerDel(Request $req)
    {
        $param = $req->all();
        $ids = isset($param['ids']) ? json_decode($param['ids'], true) : [];
        if (empty($ids)) {
            return errBack();
        }
        $res = ImEnterpriseCertification::whereIn('id', $ids)->where('status', '<>', 2)->delete();
        //添加操作日志
        if ($res) {
            OperationLogsBusiness::addLog(ImOperationLogs::DELETE, '删除企业认证;ID:' . join(',', $ids));
        }
        return okBack();
    }
}
